<template>
	<view class="matchmain animated fadeIn faster">
		<view class="position-fixed w-100 z-index-100 pb-1"
			:style="{'paddingTop':$store.state.statusBarHeight+'px','backgroundColor':bgcolor}">
			<view class="d-flex d-flex-middle d-flex-between" :style="{'height': $store.state.titleBarHeight + 'px'}">
				<view class="pl-2" :class="(DeviceType === 'App' || DeviceType === 'H5')? 'mr-5' : ''" @click="goBack">
					<text class="iconfont icon-31fanhui1 font30 colorfff"></text></view>
				<view class="colorfff text-center"
					:class="(DeviceType === 'App' || DeviceType === 'H5')? 'mr-1' : 'mr-3'" style="flex: 1;">搭子铃</view>
				<view v-if="DeviceType === 'App' || DeviceType === 'H5'" class="colorfff font26 mr-3"
					@click="gotoBellSetting">设置</view>
			</view>
		</view>
		<view :style="{paddingTop:$store.state.statusBarHeight+'px',height: $store.state.titleBarHeight + 'px'}"></view>
		<view v-if="DeviceType === 'WeChat'" class="colorfff text-right mt-3 mr-3 font26" @click="gotoBellSetting">设置
		</view>
		<view class="dazibell d-flex d-flex-center mt-6 position-relative" style="width: 100%;">
			<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%203401%402x.png"
				style="width: 420rpx; height: 188rpx;"></image>
			<view class="matchbtn position-absolute colorfff linerbg rounded30 py-1 px-1"
				style="bottom: -10rpx; letter-spacing: 5rpx;">{{flag?"快速匹配":"低速匹配"}}</view>
		</view>
		<view class="d-flex d-flex-center mb-7 mt-5 font24">
			<text class="colorfff">今天已有</text>
			<text class="colorman">1197256</text>
			<text class="colorfff">人在这里相遇</text>
		</view>
		<view class="metting-box position-absolute bottom-0">
			<view class="font34 font-bold pt-1 pl-2 linerbg-b pb-5">猜你想要奇遇的人</view>
			<view class="d-flex d-flex-between pl-3 pr-4 font30 mb-5" id="distanceLabel">
				<text>请点击筛选您想要的距离</text>
				<text style="color: #46C4FF;">0-{{distance}}km</text>
			</view>

			<!-- 进度条 -->
			<view class="ProgressStyle rounded15 position-relative" style="box-sizing: border-box; margin: 0 auto;"
				@click="onProgressBarClick" :style="{width: '680rpx'}" id="progressBarContainer">
				<view class="progress position-absolute rounded15" :style="{width: progress + '%'}" id="progressBar">
				</view>
			</view>
			<view class="pl-3 pr-4 font30 mt-4 mb-3">你想要Ta</view>
			<view class="pl-3 pr-4 d-flex d-flex-between" style="color: #46C4FF;">
				<view class="span-48 py-2 pl-5 rounded50 text-center position-relative"
					:style="{border: '1px solid #46C4FF',background: todayOnlineFlag? '#CFF0FB' : ''}"
					@click="todayOnlineFlag=!todayOnlineFlag">
					<text>当天在线</text>
					<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%201712%402x.png"
						class="position-absolute" style="width: 35rpx; height: 35rpx; left: 80rpx;"></image>
				</view>
				<view class="span-48 py-2 pl-5 text-center rounded50 position-relative"
					:style="{border: '1px solid #46C4FF',background: chatFlag? '#CFF0FB' : ''}"
					@click="chatFlag=!chatFlag">
					<text>想聊天</text>
					<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%201717%402x.png"
						class="position-absolute"
						style="width: 35rpx; height: 35rpx; left: 92rpx; top: 50%; transform: translateY(-50%);">
					</image>
				</view>
			</view>
			<view class="d-flex d-flex-between ml-4 mt-5" v-for="(i, index) in acceleratePages" :key="i.id"
				@click="selectItem(i.id, index)">
				<view class="d-flex d-flex-between d-flex-middle">
					<view class="mr-2">
						<image :src="i.icon" style="width: 90rpx; height: 90rpx;"></image>
					</view>
					<view class="font30 d-flex-column">
						<text>{{i.name}}</text>
						<text class="font22" style="color: #9D9D9E;">{{i.description}}</text>
					</view>
				</view>
				<view class="d-flex mr-4 d-flex-middle">
					<view class="mr-1">
						<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%201941.png"
							style="width: 30rpx; height: 30rpx;"></image>
					</view>
					<view class="font36 font-bold">{{device?i.androidCoinPrice:i.iosCoinPrice}}</view>
					<view class="font30 mr-1" style="color: #C7C8C9; text-decoration: line-through;">
						{{device?i.androidCoinPrice:i.iosCoinPrice}}0</view>
					<view class="mr-4">
						<view v-if="selectedId === i.id" class="ActiveRadio "></view>
						<view v-else
							style="width: 25rpx; height: 25rpx; border: 1px solid #cdcdcd; margin-right: 25rpx;"
							class="rounded"></view>
					</view>
				</view>
			</view>
			<view class="linerbg mx-4 text-center colorfff font38 py-2 rounded50 mt-7" style="box-sizing: border-box;"
				@click="submit()">帮我加速奇遇Ta</view>
		</view>
		<uni-popup ref="purchasePopup" @change="PopupStatusChange" type="bottom" background-color="#fff" border-radius="15px 15px 0 0">
			<view class="PayOptions pt-2 d-flex-between" v-for="(item, index) in PayList" :key="item.id" @click="ChangePayOpt(index)">
				<view class="d-flex d-flex-middle d-flex-between">
					<view class="icon">
						<image :src="item.icon"></image>
					</view>
					<view class="option mr-1" style="margin-bottom: 4rpx;">{{item.name}}</view>
					<view v-if="item.desc" class="font22 px-3 rounded10" style="color: #FF9645; background: #f9e7c9;">{{ item.desc }}</view>
				</view>
				<view v-if="item.checked" class="ActiveRadio"></view>
				<view 
					v-else
					style="width: 25rpx; height: 25rpx; border: 1px solid #cdcdcd; margin-right: 22rpx;"
					class="rounded"
				></view>
			</view>
			<view class="btn ml-2 colorfff linerbg" style="width: 75%;" @click="confirm">立即开通</view>
			<!-- <radio-group class="PayOptions pt-2 d-flex-between" v-for="(item, index) in PayList" :key="item.id"
				@click="ChangePayOpt(index)">
				<label class="d-flex d-flex-middle d-flex-between">
					<view class="icon">
						<image :src="item.icon"></image>
					</view>
					<view class="option mr-1" style="margin-bottom: 4rpx;">{{item.name}}</view>
					<view v-if="item.desc" class="font22 px-3 rounded10" style="color: #FF9645; background: #f9e7c9;">
						{{item.desc}}</view>
				</label>
				<radio :value="index" :checked="item.checked" style="transform:scale(0.6);"></radio>
			</radio-group> -->
			<!-- <view class="btn ml-2 colorfff linerbg" style="width: 75%;" @click="confirm">立即开通</view> -->
		</uni-popup>

		<view v-if="IsShowCoupon" class="position-fixed top-0 left-0 right-0 bottom-0"
			style="background: rgba(0, 0, 0, .4); z-index: 1001;">
			<view class="position-relative bg-fff"
				style="top: 50%; left: 50%; transform: translate(-50%,-50%); border-radius:10px 10px 10px 10px">
				<view class="coupon-list">
					<view class="font32 text-center mt-1 mb-3">您有以下的优惠券可以使用</view>
					<view v-for="(i, index) in couponList" :key="index" class="d-flex"
						style="height: 120rpx; width: 90%; margin: 0 auto 20rpx;">
						<view class="Cover rounded10" style="width: 90rpx; height: 100%;">
							<view class="d-flex d-flex-bottom d-flex-center colorfff" style="margin-top: 15rpx;">
								<view style="margin-bottom: 5rpx;">￥</view>
								<view class="font-bold" style="font-size: 40rpx;">{{ i.amount }}</view>
							</view>
							<view class="font16 mt-1 colorfff text-center">
								满{{ i.limitUseAmount == 0 ? i.amount : i.limitUseAmount }}元可用</view>
						</view>
						<view class="Coupon_item d-flex-middle d-flex bg-fff rounded10"
							style="flex: 1; padding: 10rpx;">
							<view class="d-flex d-flex-column ml-3" style="flex: 1;">
								<view class="font24 mt-1">{{ i.name }} </view>
								<view class="font24" style=" flex: 1;color: #b5b5b5;">有效期:{{ i.assetsExpireTime }}到期
								</view>
							</view>
							<view class="btn1 colorfff mr-3 px-2 rounded10 font20" @click="touse(i.assetsId)">选择</view>
						</view>
					</view>


					<view class="btn ml-2  colorfff"
						style="width: 75%; background-image: linear-gradient(-90deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);"
						@click="unuse">不使用优惠券</view>

				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { manner } from "@/util/manner.js";
	import { DaziApi } from "../../http/Dazi";
	import { PayApi } from "../../http/PayApi";
	export default {
		data() {
			return {
				bgcolor: 'transparent',
				progress: 20,
				param: {},
				PayList: [{
						id: 3,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241115141319.png',
						name: '支付宝',
						desc: '推荐',
						value: 'Alipay',
						checked: true
					},
					{
						id: 2,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/Pay-Wechat.png',
						name: '微信',
						desc: '',
						value: 'Wechat',
						checked: false
					},
					{
						id: 1,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%20554.png',
						name: '嗒币',
						desc: '',
						value: 'DaBi',
						checked: false
					}
				],
				progress: 30, // 初始进度值
				maxDistance: 10, // 最大距离
				distance: 3, // 初始距离
				todayOnlineFlag: false, //当日在线标识
				chatFlag: false, //想聊天标识
				acceleratePages: [],
				orderNo: null,
				setParam: {},
				IsShowCoupon: false,
				payType: null,
				flag: false, //支付结果
				buyParam: {},
				couponList: [],
				price: 0,
				payMethod: null,
				orderStr: null,
				WxpayParams: {}, //微信支付参数
				DeviceType: null,
				selectedId: null, // 用于存储当前选中的 ID
				device: true, //默认安卓
				selectedIndex: 0
			}
		},
		onPageScroll(e) {
			let scrollTop = e.scrollTop
			if (scrollTop > 10) {
				this.bgcolor = '#191635'
			} else {
				this.bgcolor = 'transparent'
			}
		},
		onShow() {
			uni.getStorage({
				key: 'setParam',
				success: (res) => {
					const setParam = res.data;
					this.setData(setParam);
				},
				fail: () => {
					console.log('没有找到数据');
					// 如果没有找到数据，可以选择不做任何操作
				}
			});
		},
		onLoad() {
			let systemInfo = uni.getSystemInfoSync();
			if (systemInfo.platform === 'ios') {
				this.device = false;
				console.log('当前设备是苹果设备');
			} else if (systemInfo.platform === 'android') {
				this.device = true;
				console.log('当前设备是安卓设备');
			}
			this.getaccelerate();
			// #ifdef APP-PLUS
			this.DeviceType = 'App'
			// #endif

			// #ifdef H5
			this.DeviceType = 'H5'
			// #endif

			// #ifdef MP-WEIXIN
			this.DeviceType = 'WeChat'
			// #endif
		},
		methods: {
			onProgressBarClick(event) {
				const query = uni.createSelectorQuery().in(this);
				query.select('#progressBarContainer').boundingClientRect(rect => {
					if (rect) {
						const clickPosition = event.detail.x - rect.left;
						const newPercentage = (clickPosition / rect.width) * 100;
						this.progress = newPercentage;
						this.distance = (newPercentage / 100) * this.maxDistance;
						this.distance = parseFloat(((newPercentage / 100) * this.maxDistance).toFixed(1));
					}
				}).exec();
			},
			selectItem(id, index) {
				this.selectedId = id;
				this.selectedIndex = index
			},
			async getCoupon() { //查询可用优惠券
				const param = {
					resourceType: 12,
					amount: this.price
				};
				this.couponList = [];
				const res = await PayApi.getCoupon(param);
				this.couponList = res;
				console.log(this.couponList);




			},
			ChangePayOpt(dex) {
				console.log(dex);
				this.PayList[dex].checked = true;
				this.PayList.forEach((i, index) => {
					if (dex !== index) {
						this.PayList[index].checked = false;
					}
				});
			},

			async setAccelerate(param) { //设置
				let res = await DaziApi.setAccelerate(param);
			},
			async buyAccelerate(param) { //购买
				let res = await DaziApi.buyAccelerate(param);
				this.orderNo = res.orderNo;

			},
			async Pay(orderNo, payMethod) {
				let params = {
					orderNo: orderNo,
					payMethod: payMethod,
					payType: this.payType
				}
				const res = await PayApi.Pay(params)
				console.log(res);
				console.log(payMethod);
				if (payMethod == 3) {
					this.orderStr = res.params.orderStr;
					this.payByAlipay();
					return
				}
				if (payMethod == 2) { //微信支付
					this.WxpayParams = {};
					this.WxpayParams = res.params;

					this.payByWxpay();
					return
				}
				if (params.payType == 1) {
					console.log(res.paySuccess);
					if (res.paySuccess) {
						uni.showToast({
							title: '购买成功',
							icon: 'none', // 使用'none'图标，只显示文字
							duration: 1000 // 显示持续时间
						});
						this.flag = true;
						this.$refs.purchasePopup.close();

					}
				}


			},

			confirm() {
				let that = this
				let payMethod = null
				that.PayList.forEach(i => {
					if (i.checked) {

						payMethod = i.id,
							that.payType = (i.id == 1) ? 1 : 2
					}
				})




				uni.showModal({
					content: '确认支付？',
					success: function(res) {
						// 关闭弹窗--创建订单
						if (res.confirm) {
							// that.$refs.purchasePopup.close()

							that.Pay(that.orderNo, payMethod)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			payByWxpay() {
				uni.requestPayment({
					"provider": "wxpay", // 微信支付
					"orderInfo": {
						"appid": this.WxpayParams.appid,
						"timestamp": this.WxpayParams.timestamp,
						"noncestr": this.WxpayParams.noncestr,
						"package": "Sign=WXPay",
						"partnerid": this.WxpayParams.partnerId,
						"prepayid": this.WxpayParams.prepayId,
						"sign": this.WxpayParams.sign
					},

					success: (res) => {
						console.log('支付成功', res);
						this.flag = true;
						this.$refs.purchasePopup.close();
						// 支付成功的处理逻辑
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 2000
						});
					},
					fail: (err) => {
						console.log('支付失败，错误信息：', err);
						if (err.errCode === 'xxx') {
							// 可以根据不同的 errCode 进行不同的处理，这里的 xxx 是具体的错误码，例如用户取消支付的错误码
							console.log('用户取消支付');
						} else if (err.errCode === 'yyy') {
							// 另一种错误码 yyy 的处理
							console.log('签名错误，请联系客服');
						} else {
							console.log('其他支付错误，请重试或联系客服');
						}
						uni.showToast({
							title: '支付失败',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			OpencouponPopup() {
				this.IsShowCoupon = true
			},
			payByAlipay() { //支付宝的支付

				const orderStr = this.orderStr;
				if (!orderStr) {
					console.error('订单字符串为空，无法进行支付');
					return;
				}

				// 调用 uni.requestPayment 方法
				uni.requestPayment({
					provider: 'alipay', // 指定支付提供商为支付宝
					orderInfo: orderStr, // 订单信息
					success: (res) => {
						console.log('支付成功:', res);
						this.flag = true;
						this.$refs.purchasePopup.close();
						uni.showToast({
							title: '支付成功',
							icon: 'none', // 使用'none'图标，只显示文字
							duration: 1000 // 显示持续时间
						});

					},
					fail: (err) => {
						console.error('支付失败:', err);
						uni.showToast({
							title: '支付失败',
							icon: 'none', // 使用'none'图标，只显示文字
							duration: 1000 // 显示持续时间
						});
					}
				});
			},
			unuse() {
				this.IsShowCoupon = false;
				this.buyParam = {};
				this.buyParam.sourceType = this.device ? 1 : 2;
				this.buyParam.id = this.selectedId;
				this.buyParam.type = this.selectedId;


				this.buyAccelerate(this.buyParam);
				this.OpenpurchasePopup();
			},
			touse(id) { //使用优惠券
				console.log(id);
				// 选择优惠券后继续支付流程

				this.buyParam.couponAssetsId = id;
				this.buyParam.sourceType = this.device ? 1 : 2;
				this.buyParam.id = this.selectedId;
				this.buyParam.type = this.selectedId;
				console.log(this.param);

				this.buyAccelerate(this.buyParam);

				this.IsShowCoupon = false;
				this.OpenpurchasePopup();

			},
			async submit() {
				if (this.selectedId == null) {
					uni.showToast({
						title: '请选择加速套餐',
						icon: 'none', // 使用'none'图标，只显示文字
						duration: 1000 // 显示持续时间
					});
					return;
				}
				this.price = this.device ? this.acceleratePages[this.selectedIndex].androidPrice : this
					.acceleratePages[this.selectedIndex].iosPrice;
				this.setParam.distanceFrom = 0;
				this.setParam.distanceTo = this.distance;
				this.setParam.todayOnlineFlag = this.todayOnlineFlag;
				this.setParam.chatFlag = this.chatFlag;
				console.log("修改设置入参：", this.setParam);
				this.setAccelerate(this.setParam);
				this.buyParam.sourceType = this.device ? 1 : 2;
				this.buyParam.id = this.selectedId;
				this.buyParam.type = this.selectedId;
				await this.getCoupon();
				if (this.couponList.length > 0) {
					this.OpencouponPopup();
				} else {
					this.buyAccelerate(this.buyParam);
					this.OpenpurchasePopup();
				}
			},
			OpenpurchasePopup() {
				this.$refs.purchasePopup.open('bottom')

			},
			setData(newData) {
				this.setParam = newData;

				uni.removeStorage({
					key: 'setParam'
				});
			},
			goBack() {
				manner.goBack()
			},
			async getaccelerate() { //获取加速套餐
				let res = await DaziApi.getAccelerate();

				this.acceleratePages = res.records;

				// console.log(this.acceleratePages);
			},
			gotoBellSetting() {
				uni.navigateTo({
					url: '/pagesMain/bell-setting/bell-setting'
				})
			}
		},
	}
</script>

<style scoped lang="scss">
	.coupon-list {
		padding: 20rpx;
	}

	.Cover {
		width: 90rpx;
		height: 100%;
		border-right: 1px dashed #f5f5f5;
		background-image: linear-gradient(135deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);
	}

	.Coupon_item {
		flex: 1;
		box-shadow: 3px 3px 3px rgba(0, 0, 0, .1);
	}

	.btn1 {
		height: 40rpx !important;
		line-height: 40rpx !important;
		background-image: linear-gradient(-90deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);
	}

	.PayOptions {
		width: 680rpx;
		margin: 0 auto;
		display: flex;
		align-items: center;
		margin-top: 30rpx;

		.icon {
			margin-right: 26rpx;

			image {
				width: 64rpx;
				height: 64rpx;
			}
		}

		.option {
			color: #231815;
			font-size: 28rpx;
		}
	}

	.btn {
		margin: 40rpx auto 20rpx;
		text-align: center;
		font-size: 30rpx;
		height: 87rpx;
		line-height: 87rpx;
		border-radius: 50rpx;
	}

	.matchmain {
		background-image: url('https://168809.oss-cn-hangzhou.aliyuncs.com/community/temp/machbg.png');
		background-repeat: no-repeat;
		background-size: cover;
		background-position: 0 100%;
		min-height: 100vh;
	}

	.metting-box {
		width: 98%;
		height: 940rpx;
		left: 50%;
		transform: translateX(-50%);
		border-radius: 50rpx 50rpx 0 0;
		background-color: #fff;
		overflow: hidden;
	}

	.linerbg-b {
		background: linear-gradient(180deg, #61D1E5 0%, rgba(106, 211, 230, 0.94) 10%, rgba(131, 219, 234, 0.78) 29%, rgba(172, 230, 241, 0.52) 54%, rgba(227, 247, 250, 0.17) 86%, rgba(255, 255, 255, 0) 100%);
	}

	.colorman {
		color: #5db0fe
	}

	.ProgressStyle {
		background: linear-gradient(90deg, #F6F7F9 0%, #EBF2F5 33%, #D0E4EA 89%, #CBE2E8 100%);
		box-sizing: border-box;
		height: 24rpx;
		width: 680rpx;
	}

	.progress {
		background: linear-gradient(90deg, #FF389C 0%, #FFA867 60%, #FFEF46 100%);
		top: 0;
		left: 0;
		height: 100%;
	}
	.ActiveRadio {
		margin-right: 20rpx;
		width: 32rpx;
		height: 32rpx;
		border-radius: 50%;
		background-image: url(https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E5%8B%BE%E9%80%89.png);
		background-repeat: no-repeat;
		background-size: 100% 100%;
	}
</style>